﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebFabricator.org
{
    /// <summary>
    /// Create an object model around the Namespace syntax used by the fabric
    /// </summary>
    public class Namespace : Uri, IComparable<Namespace>
    {

        public string Scope
        {
            get;
            private set;
        }

        public string LocalName
        {
            get;
            private set;
        }

        public Char Separator
        {
            get;
            private set;
        }

        public Namespace(String value):base(value, UriKind.Absolute)
        {
            switch(Scheme)
            {
                case "urn":
                    Separator = ':';
                break;
                default:
                    Separator = '/';
                break;
            }
            int index = value.LastIndexOf(Separator) > -1 ? value.LastIndexOf(Separator) : 0;
            Scope = value.Substring(0, index);
            LocalName = value.Substring(index, value.Length - index).TrimStart(Separator);
        }

        public static bool TryCreate(string value, out Namespace @namespace)
        {
            @namespace = null;
            try
            {
                @namespace = new Namespace(value);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static implicit operator Namespace(string value)
        {
            Namespace n;
            Namespace.TryCreate(value, out n);
            return n;
        }

        public int CompareTo(Namespace other)
        {
            int comparison =  this.GetBigHashCode().CompareTo(other.GetBigHashCode());
            if (comparison == 0)
                comparison = string.Compare(this.Normalize().ToString(), other.Normalize().ToString());
            return comparison;
        }

       
    }
}
